<template>
  <div>
    <div class="search-bar">
      <!-- 添加区域按钮 -->
      <el-row gutter="20">
        <el-col :span="4" :offset="6">
          <el-button type="primary" @click="showAddArea">添加区域</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 区域表格模态框 -->
    <el-table :data="areas" empty-text="暂无数据" style="width: 45%">
      <el-table-column prop="areaCodeId" label="ID"></el-table-column>
      <el-table-column prop="areaCodeName" label="区域名称"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="mini" type="danger" @click="deleteArea(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加区域模态框 -->
    <el-dialog v-model="addAreaVisible" width="30%" :before-close="handleClose">
      <el-form :model="form" :rules="rules" ref="addFormRef">
        <span class="bold-large">添加区域</span>
        <el-form-item label="区域名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <div class="dialog-footer">
          <el-button @click="cancelForm('addFormRef')">取 消</el-button>
          <el-button type="primary" @click="submitForm('addFormRef')">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import {
  ElTable,
  ElTableColumn,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElDialog
} from 'element-plus';
import axios from 'axios';

export default {
  components: {
    ElTable,
    ElTableColumn,
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
    ElDialog,
  },
  data() {
    return {
      areas: [],
      form: {
        name: ''
      },
      rules: {
        name: [
          {required: true, message: '请输入区域名称', trigger: 'blur'},
          {min: 1, max: 10, message: '区域名称长度在1-10位之间', trigger: 'blur'}
        ]
      },
      addAreaVisible: false,
    };
  },
  created() {
    this.fetchAreas();
  },
  methods: {
    showAddArea() {
      this.addAreaVisible = true;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 添加操作
          this.addArea().then(() => {
            this.resetForm(formName);
            this.addAreaVisible = false;
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.form.name = '';
    },
    deleteArea(index, row) {
      this.deleteAreaById(row.areaCodeId).then(() => {
        this.areas.splice(index, 1);
      });
    },
    handleClose(done) {
      this.resetForm('addFormRef');
      done();
    },
    cancelForm(formName) {
      this.resetForm(formName);
      this.addAreaVisible = false;
    },
    fetchAreas() {
      axios.get('/user/areaCode/listAreaCode')
          .then(response => {
            // 对数据按 id 进行排序
            this.areas = response.data.data.sort((a, b) => a.areaCodeId - b.areaCodeId);
          })
          .catch(error => {
            console.error('Error fetching areas:', error);
          });
    },
    addArea() {
      const data = {
        areaCode: this.form.name
      };
      return axios.post('/user/areaCode/addAreaCode', data, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
          .then(response => {
            if (response.data.code === 200) {
              this.fetchAreas();
              return true;
            } else {
              alert('添加失败');
              return false;
            }
          })
          .catch(error => {
            console.error('Error adding area:', error);
            alert('添加失败');
            return false;
          });
    },
    deleteAreaById(areaCodeId) {
      return axios.delete(`/user/areaCode/deleteAreaCode?areaCodeId=${areaCodeId}`)
          .then(response => {
            if (response.data.code === 200) {
              alert(response.data.msg);
              this.fetchAreas();
              return true;
            } else {
              alert('删除失败');
              return false;
            }
          })
          .catch(error => {
            console.error('Error deleting area:', error);
            alert('删除失败');
            return false;
          });
    },
  },
};
</script>

<style scoped>
.bold-large {
  font-weight: bold;
  font-size: 1.5em; /* 调整字体大小，可以根据需要调整 */
}
.search-bar {
  width: 100%;
  margin-bottom: 15px;
}
</style>
